    import * as THREE from 'three'
    import gsap from 'gsap';
    import {
        MySprite
    } from '@/model/MySprite'
    import { ClickHandler } from '@/utils/ClickHandler'
    import { EventBus } from '@/utils/EventBus'

export class Car {
    constructor(model, scene, camera, controls) {
        this.model = model;
        this.scene = scene;
        this.camera = camera;
        this.controls = controls;

        this.carModel = {
            'body': {
                'main': { // 车身
                    name: 'Object_103',
                    model: {}, // 小物体对象
                },
                'roof': { // 车顶
                    name: 'Object_110',
                    model: {}, // 小物体对象
                },
                'leftDoor': { // 左车门
                    name: 'Object_64',
                    model: {},
                    mark: [
                        {
                            name: 'sprite',
                            url: './image/sprite.png',
                            position: [1.07, 1.94, -0.23],
                            scale: [0.2, 0.2],
                        }
                    ]
                },
                'rightDoor': { // 右车门
                    name: 'Object_77',
                    model: {},
                    mark: [
                        {
                            name: 'sprite',
                            url: './image/sprite.png',
                            position: [-1.05, 0.78, -0.23],
                            scale: [0.2, 0.2],
                        }
                    ]
                }
            },
            'glass': { // 玻璃
                'front': {
                    name: 'Object_90',
                    model: {}
                },
                'leftGlass': { // 左玻璃
                    name: 'Object_68',
                    model: {}
                },
                'rightGlass': { // 右玻璃
                    name: 'Object_81',
                    model: {}
                }
            }
        }

        this.info = {
            // 颜色
            color: [
                {
                    name: '土豪金',
                    color: '#ff9900',
                    isSelected: true,
                },
                {
                    name: '传奇黑',
                    color: '#343a40',
                    isSelected: false,
                },
                {
                    name: '玫瑰紫',
                    color: '#6600ff',
                    isSelected: false,
                },
                {
                    name: '银灰色',
                    color: '#DCDFE6',
                    isSelected: false,
                }
            ],
            // 贴膜
            film: [
                {
                    name: '高光',
                    price: 0,
                    isSelected: true
                },
                {
                    name: '磨砂',
                    price: 20000,
                    isSelected: false
                }
            ],
            // 总价
            allPrice: 2444700
        }
        // 汽车视角
        this.positionObj = {
            // 主驾驶位
            main: {
                camera: {
                    x: 0.36,
                    y: 0.96,
                    z: -0.16
                },
                controls: {
                    x: 0.36,
                    y: 0.87,
                    z: 0.03
                }
            },
            // 副驾驶位
            copilot: {
                camera: {
                    x: -0.39,
                    y: 0.87,
                    z: 0.07
                },
                controls: {
                    x: -0.39,
                    y: 0.85,
                    z: 0.13
                },
            },
            // 外面观察
            outside: {
                camera: {
                    x: 3,
                    y: 1.5,
                    z: 3
                },
                controls: {
                    x: 0,
                    y: 0,
                    z: 0
                },
            }
        }

        // 初始化
        this.init()

        // 修改汽车的默认配置
        this.modifyCarDefault()

        // 添加精灵物体
        this.createDoorSprite()

        // 注册修改颜色
        EventBus.getInstance().on('changeCarColor', (colorStr) => {
            // 修改车身所有的颜色
            Object.values(this.carModel.body).forEach(obj => {
                obj.model.material.color = new THREE.Color(colorStr)
            })
        
            // 保存用户选择的车颜色
            this.info.color.forEach(obj => {
                obj.isSelected = false
                if (obj.color === colorStr) {
                    obj.isSelected = true
                }
            })
        })

        // 注册修改贴膜
        EventBus.getInstance().on('changeCarCoat', (coatName) => {
            if (coatName === '高光') {
                Object.values(this.carModel.body).forEach(obj => {
                   obj.model.material.roughness = 0.5
                   obj.model.material.metalness = 1
                   obj.model.material.clearcoat = 1
                })
            } else if (coatName === '磨砂') {
                Object.values(this.carModel.body).forEach(obj => {
                   obj.model.material.roughness = 1
                   obj.model.material.metalness = 0.7
                   obj.model.material.clearcoat = 0
                })
            }

            Object.values(this.info.film).forEach(obj => {
                obj.isSelected = false
                if (obj.name === coatName) {
                  obj.isSelected = true
                }
            })
        })

        // 注册修改价格
        EventBus.getInstance().on('celPrice', () => {
            // 当前贴膜的价格
            let filmTarget = this.info.film.find(item => item.isSelected)
            const cellPrice = this.info.allPrice + filmTarget.price
            let priceSpan = document.querySelector('.price > span')
            priceSpan.innerText = `￥${cellPrice.toFixed(2)}`
        })

        // 注册修改视角
        EventBus.getInstance().on('changeCarAngleView', (viewName) => {
            this.setCameraAnimation(this.positionObj[viewName])
        })
    }
    init () {
        this.scene.add(this.model)
        Object.values(this.carModel.body).forEach(obj => {
            obj.model = this.model.getObjectByName(obj.name)
        })
        Object.values(this.carModel.glass).forEach(obj => {
            obj.model = this.model.getObjectByName(obj.name)
        })
    }

    modifyCarDefault () {
        const carMaterial = new THREE.MeshPhysicalMaterial({
            color: 0xff9900,
            roughness: 0.5,
            metalness: 1,
            clearcoat: 1,
            clearcoatRoughness: 0
        })
        Object.values(this.carModel.body).forEach(obj => {
            obj.model.material = carMaterial
        })
        // 修改前 左 右的玻璃
        Object.values(this.carModel.glass).forEach(obj => {
            obj.model.material.side = THREE.FrontSide // 只渲染前面
        })
        // 修改 顶部的玻璃
        this.carModel.body.roof.model.material.side = THREE.DoubleSide
    }

    // 添加精灵物体
    createDoorSprite () {
        const markList = [
            this.carModel.body.leftDoor,
            this.carModel.body.rightDoor
        ]
        markList.forEach(obj => {
            // 遍历车门标记，添加附加物体
            obj.mark.forEach(smallObj => {
                if (smallObj.name === 'sprite') {
                    // 创建精灵物体，添加到小模型上
                    const sprite = new MySprite(smallObj)
                    obj.model.add(sprite)
                    // addMesh方法把当前精灵物体添加到clickHandler里面的list数组中，在那里会通过射线，收集三维物体
                    ClickHandler.getInstance().addMesh(sprite, (clickThreeObj) => {
                        // 注意，只有clickThreeObj的parent.parent.parent的旋转的中心点是正确的
                        const targetDoor = clickThreeObj.parent.parent.parent
                        // userData是自定义的数据，isOpen是我们添加的属性
                        if (!targetDoor.userData.isOpen) {
                            // 调用了旋转的动画
                            this.setDoorAnimatie(targetDoor, {
                                x: Math.PI / 3
                            })
                            targetDoor.userData.isOpen = true
                        } else {
                            this.setDoorAnimatie(targetDoor, {
                                x: 0
                            })
                            targetDoor.userData.isOpen = false
                        }
                    })
                }
            })
        })

    }

    // gsap进行过渡旋转
    setDoorAnimatie (mesh, obj) {
        gsap.to(mesh.rotation, {
            x: obj.x,
            duration: 1,
            ease: 'power1.in'
        })
    }

    // 添加摄像机和轨道控制器
    setCameraAnimation (dataObj) {
        gsap.to(this.camera.position, {
            ...dataObj.camera, 
            duration: 1,
            ease: 'power1.in'
        })
        gsap.to(this.controls.target, {
            ...dataObj.controls, 
            duration: 1,
            ease: 'power1.in'
        })
    }
}

